import { DataItem, DelDataRequest, FastResponse } from "../models/dataprops";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { X } from "lucide-react";
import { postData } from "../utils/api";

export interface DataCardProps {
  data: DataItem;
  onDelete: () => void;
}
export const DataCard: React.FC<DataCardProps> = ({ data, onDelete }) => {
  const {
    id,
    name,
    des,
    data_from,
    data_type,
    uploader,
    data_path,
    update_time,
  } = data;
  const handleClick = async () => {
    const payload: DelDataRequest = {
      data_name: name,
      data_path: data_path,
    };

    try {
      const result = await postData<FastResponse<DataItem>, DelDataRequest>(
        "/data/delete",
        payload
      ); // 泛型定义请求和响应类型
      if (result.code === 200) {
        console.log("删除成功");
        onDelete();
      } else {
        console.error("删除失败");
      }
    } catch (error) {
      console.error("Error submitting data:", error);
    }
  };

  return (
    <Card
      key={id}
      className="group relative flex flex-col justify-between w-64 h-64 cursor-pointer hover:border-green-100 hover:bg-green-50"
    >
      <CardHeader>
        <CardTitle className="flex justify-between">
          {name}
          <button
            className="opacity-0 rounded-md  text-gray-500 hover:text-red-700 group-hover:opacity-100 transition-opacity duration-300"
            onClick={handleClick}
          >
            <X className="w-4 h-4" />
          </button>
        </CardTitle>
        <CardDescription className="text-xs">创建人:{uploader}</CardDescription>
      </CardHeader>
      <CardContent className="flex flex-grow text-sm">
        <p>{des.length > 100 ? des.slice(0, 100) + "..." : des}</p>
      </CardContent>
      <CardFooter className="mt-auto flex flex-col items-start gap-1 ">
        <div className="text-xs text-gray-500">
          数据地址:{" "}
          {data_path.length > 20
            ? "/DF" + data_path.slice(13, data_path.length)
            : data_path}
        </div>
        <div className="text-xs text-gray-500">
          更新时间:{update_time.replace("T", " ")}
        </div>
        <div className="flex gap-2 pt-1">
          <Badge
            variant="outline"
            className={
              data_from === "自建数据" ? "bg-green-200" : "bg-lime-200"
            }
          >
            {data_from}
          </Badge>
          <Badge
            variant="outline"
            className={
              data_type === "调优数据" ? "bg-rose-200" : "bg-fuchsia-200"
            }
          >
            {data_type}
          </Badge>
        </div>
      </CardFooter>
    </Card>
  );
};
